using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Logging;
using Volo.Abp;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Application.Services;
using Volo.Abp.BackgroundJobs;
using Volo.Abp.Caching;
using Volo.Abp.Data;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.EventBus.Distributed;
using Volo.Abp.MultiTenancy;
using Volo.Abp.Uow;
using System.Text.Json;
using TenantManagementService.Tenants;
using TenantManagementService.Events;
using TenantManagementService.Localization;

namespace TenantManagementService.Tenants
{
    /// <summary>
    /// 租户管理应用服务实现
    /// </summary>
    [Authorize]
    public class TenantAppService : CrudAppService<
        Tenant,
        TenantDto,
        Guid,
        PagedAndSortedResultRequestDto,
        CreateTenantDto,
        UpdateTenantDto>, ITenantAppService
    {
        protected ITenantRepository TenantRepository { get; }
        protected IRepository<TenantConfiguration, Guid> ConfigurationRepository { get; }
        protected IDistributedCache<TenantCacheItem> TenantCache { get; }
        protected IBackgroundJobManager BackgroundJobManager { get; }
        protected IDistributedEventBus EventBus { get; }
        protected ICurrentTenant CurrentTenant { get; }
        protected IUnitOfWorkManager UnitOfWorkManager { get; }

        public TenantAppService(
            IRepository<Tenant, Guid> repository,
            ITenantRepository tenantRepository,
            IRepository<TenantConfiguration, Guid> configurationRepository,
            IDistributedCache<TenantCacheItem> tenantCache,
            IBackgroundJobManager backgroundJobManager,
            IDistributedEventBus eventBus,
            ICurrentTenant currentTenant,
            IUnitOfWorkManager unitOfWorkManager) : base(repository)
        {
            TenantRepository = tenantRepository;
            ConfigurationRepository = configurationRepository;
            TenantCache = tenantCache;
            BackgroundJobManager = backgroundJobManager;
            EventBus = eventBus;
            CurrentTenant = currentTenant;
            UnitOfWorkManager = unitOfWorkManager;
        }

        /// <summary>
        /// 根据编码获取租户
        /// </summary>
        public async Task<TenantDto> GetByCodeAsync(string code)
        {
            var tenant = await TenantRepository.GetByCodeAsync(code);
            return ObjectMapper.Map<Tenant, TenantDto>(tenant);
        }

        /// <summary>
        /// 激活租户
        /// </summary>
        [Authorize(TenantManagementPermissions.Tenants.Manage)]
        public async Task<TenantDto> ActivateAsync(Guid id)
        {
            var tenant = await TenantRepository.GetAsync(id);

            // 检查租户状态
            if (tenant.Status == TenantStatus.Active)
            {
                throw new BusinessException("TenantManagement:TenantAlreadyActive")
                    .WithData("TenantId", id);
            }

            var oldStatus = tenant.Status;
            var isFirstActivation = !tenant.LastActivationTime.HasValue;

            tenant.Activate();
            await TenantRepository.UpdateAsync(tenant);

            // 清除缓存
            await TenantCache.RemoveAsync(tenant.Id.ToString());

            // 发布事件
            await EventBus.PublishAsync(new TenantActivatedEvent
            {
                TenantId = tenant.Id,
                Code = tenant.Code,
                Name = tenant.Name,
                ActivationTime = DateTime.Now,
                ActivatedBy = CurrentUser.Id?.ToString(),
                IsFirstActivation = isFirstActivation
            });

            await EventBus.PublishAsync(new TenantStatusChangedEvent
            {
                TenantId = tenant.Id,
                Code = tenant.Code,
                Name = tenant.Name,
                OldStatus = oldStatus,
                NewStatus = tenant.Status,
                ChangeTime = DateTime.Now,
                ChangedBy = CurrentUser.Id?.ToString(),
                Reason = "Manual activation"
            });

            Logger.LogInformation("租户已激活: {TenantCode} ({TenantId})", tenant.Code, tenant.Id);

            return ObjectMapper.Map<Tenant, TenantDto>(tenant);
        }

        /// <summary>
        /// 暂停租户
        /// </summary>
        [Authorize(TenantManagementPermissions.Tenants.Manage)]
        public async Task<TenantDto> SuspendAsync(Guid id, string? reason = null)
        {
            var tenant = await TenantRepository.GetAsync(id);

            var oldStatus = tenant.Status;
            tenant.Suspend();
            await TenantRepository.UpdateAsync(tenant);

            // 清除缓存
            await TenantCache.RemoveAsync(tenant.Id.ToString());

            // 发布事件
            await EventBus.PublishAsync(new TenantStatusChangedEvent
            {
                TenantId = tenant.Id,
                Code = tenant.Code,
                Name = tenant.Name,
                OldStatus = oldStatus,
                NewStatus = tenant.Status,
                ChangeTime = DateTime.Now,
                ChangedBy = CurrentUser.Id?.ToString(),
                Reason = reason ?? "Manual suspension"
            });

            Logger.LogInformation("租户已暂停: {TenantCode} ({TenantId})", tenant.Code, tenant.Id);

            return ObjectMapper.Map<Tenant, TenantDto>(tenant);
        }

        /// <summary>
        /// 禁用租户
        /// </summary>
        [Authorize(TenantManagementPermissions.Tenants.Manage)]
        public async Task<TenantDto> DisableAsync(Guid id, string? reason = null)
        {
            var tenant = await TenantRepository.GetAsync(id);

            var oldStatus = tenant.Status;
            tenant.Disable();
            await TenantRepository.UpdateAsync(tenant);

            // 清除缓存
            await TenantCache.RemoveAsync(tenant.Id.ToString());

            // 发布事件
            await EventBus.PublishAsync(new TenantDeactivatedEvent
            {
                TenantId = tenant.Id,
                Code = tenant.Code,
                Name = tenant.Name,
                DeactivationTime = DateTime.Now,
                Reason = reason ?? "Manual deactivation",
                DeactivatedBy = CurrentUser.Id?.ToString(),
                IsForceDeactivation = false
            });

            Logger.LogInformation("租户已禁用: {TenantCode} ({TenantId})", tenant.Code, tenant.Id);

            return ObjectMapper.Map<Tenant, TenantDto>(tenant);
        }

        /// <summary>
        /// 启用租户
        /// </summary>
        [Authorize(TenantManagementPermissions.Tenants.Manage)]
        public async Task<TenantDto> EnableAsync(Guid id)
        {
            var tenant = await TenantRepository.GetAsync(id);

            var oldStatus = tenant.Status;
            tenant.Enable();
            await TenantRepository.UpdateAsync(tenant);

            // 清除缓存
            await TenantCache.RemoveAsync(tenant.Id.ToString());

            Logger.LogInformation("租户已启用: {TenantCode} ({TenantId})", tenant.Code, tenant.Id);

            return ObjectMapper.Map<Tenant, TenantDto>(tenant);
        }

        /// <summary>
        /// 续期租户
        /// </summary>
        [Authorize(TenantManagementPermissions.Tenants.Manage)]
        public async Task<TenantDto> ExtendSubscriptionAsync(Guid id, ExtendSubscriptionDto input)
        {
            var tenant = await TenantRepository.GetAsync(id);

            tenant.ExtendSubscription(TimeSpan.FromDays(input.Days));
            await TenantRepository.UpdateAsync(tenant);

            // 清除缓存
            await TenantCache.RemoveAsync(tenant.Id.ToString());

            // 发布事件
            await EventBus.PublishAsync(new TenantSubscriptionExtendedEvent
            {
                TenantId = tenant.Id,
                Code = tenant.Code,
                Name = tenant.Name,
                ExtensionDays = input.Days,
                NewSubscriptionEndTime = tenant.SubscriptionEndTime!.Value,
                ExtensionTime = DateTime.Now,
                ExtendedBy = CurrentUser.Id?.ToString(),
                ExtensionCount = tenant.ExtensionCount,
                PaymentInfo = input.PaymentInfo
            });

            Logger.LogInformation("租户已续期: {TenantCode} ({TenantId}) 续期 {Days} 天",
                tenant.Code, tenant.Id, input.Days);

            return ObjectMapper.Map<Tenant, TenantDto>(tenant);
        }

        /// <summary>
        /// 设置试用
        /// </summary>
        [Authorize(TenantManagementPermissions.Tenants.Manage)]
        public async Task<TenantDto> SetTrialAsync(Guid id, SetTrialDto input)
        {
            var tenant = await TenantRepository.GetAsync(id);

            tenant.SetTrialInfo(input.StartTime, input.EndTime);
            // 注意：MaxUserCount和MaxStorageSize需要通过Domain方法设置，这里暂时注释
            // tenant.MaxUserCount = input.MaxUserCount;
            // tenant.MaxStorageSize = input.MaxStorageSize;

            // 设置功能限制
            var featureSwitches = new Dictionary<string, bool>();
            foreach (var limitation in input.FeatureLimitations)
            {
                featureSwitches[limitation] = false;
            }
            tenant.UpdateFeatureSwitches(JsonSerializer.Serialize(featureSwitches));

            await TenantRepository.UpdateAsync(tenant);

            // 清除缓存
            await TenantCache.RemoveAsync(tenant.Id.ToString());

            Logger.LogInformation("租户已设置试用: {TenantCode} ({TenantId}) 试用期: {StartTime} - {EndTime}",
                tenant.Code, tenant.Id, input.StartTime, input.EndTime);

            return ObjectMapper.Map<Tenant, TenantDto>(tenant);
        }

        /// <summary>
        /// 设置管理员信息
        /// </summary>
        [Authorize(TenantManagementPermissions.Tenants.Manage)]
        public async Task<TenantDto> SetAdminInfoAsync(Guid id, SetAdminInfoDto input)
        {
            var tenant = await TenantRepository.GetAsync(id);

            tenant.SetAdminInfo(input.AdminEmail, input.AdminPhoneNumber);
            await TenantRepository.UpdateAsync(tenant);

            // 清除缓存
            await TenantCache.RemoveAsync(tenant.Id.ToString());

            Logger.LogInformation("租户管理员信息已更新: {TenantCode} ({TenantId})",
                tenant.Code, tenant.Id);

            return ObjectMapper.Map<Tenant, TenantDto>(tenant);
        }

        /// <summary>
        /// 设置连接信息
        /// </summary>
        [Authorize(TenantManagementPermissions.Tenants.Manage)]
        public async Task<TenantDto> SetConnectionInfoAsync(Guid id, SetConnectionInfoDto input)
        {
            var tenant = await TenantRepository.GetAsync(id);

            // 如果需要测试连接
            if (input.TestConnection && !string.IsNullOrEmpty(input.ConnectionString))
            {
                await TestDatabaseConnectionAsync(input.ConnectionString);
            }

            tenant.SetConnectionInfo(input.ConnectionString, input.Host);
            await TenantRepository.UpdateAsync(tenant);

            // 清除缓存
            await TenantCache.RemoveAsync(tenant.Id.ToString());

            Logger.LogInformation("租户连接信息已更新: {TenantCode} ({TenantId})",
                tenant.Code, tenant.Id);

            return ObjectMapper.Map<Tenant, TenantDto>(tenant);
        }

        /// <summary>
        /// 更新租户设置
        /// </summary>
        [Authorize(TenantManagementPermissions.Tenants.Manage)]
        public async Task<TenantDto> UpdateSettingsAsync(Guid id, UpdateTenantSettingsDto input)
        {
            var tenant = await TenantRepository.GetAsync(id);

            if (input.Settings != null)
                tenant.UpdateSettings(JsonSerializer.Serialize(input.Settings));

            if (input.CustomProperties != null)
                tenant.UpdateCustomProperties(JsonSerializer.Serialize(input.CustomProperties));

            // 注意：MaxUserCount和MaxStorageSize需要通过Domain方法设置，这里暂时注释
            // if (input.MaxUserCount.HasValue)
            //     tenant.MaxUserCount = input.MaxUserCount.Value;

            // if (input.MaxStorageSize.HasValue)
            //     tenant.MaxStorageSize = input.MaxStorageSize.Value;

            await TenantRepository.UpdateAsync(tenant);

            // 清除缓存
            await TenantCache.RemoveAsync(tenant.Id.ToString());

            Logger.LogInformation("租户设置已更新: {TenantCode} ({TenantId})",
                tenant.Code, tenant.Id);

            return ObjectMapper.Map<Tenant, TenantDto>(tenant);
        }

        /// <summary>
        /// 更新功能开关
        /// </summary>
        [Authorize(TenantManagementPermissions.Tenants.Manage)]
        public async Task<TenantDto> UpdateFeatureSwitchesAsync(Guid id, UpdateFeatureSwitchesDto input)
        {
            var tenant = await TenantRepository.GetAsync(id);

            if (input.FeatureSwitches != null)
                tenant.UpdateFeatureSwitches(JsonSerializer.Serialize(input.FeatureSwitches));

            await TenantRepository.UpdateAsync(tenant);

            // 清除缓存
            await TenantCache.RemoveAsync(tenant.Id.ToString());

            Logger.LogInformation("租户功能开关已更新: {TenantCode} ({TenantId})",
                tenant.Code, tenant.Id);

            return ObjectMapper.Map<Tenant, TenantDto>(tenant);
        }

        /// <summary>
        /// 更新主题设置
        /// </summary>
        [Authorize(TenantManagementPermissions.Tenants.Manage)]
        public async Task<TenantDto> UpdateThemeSettingsAsync(Guid id, UpdateThemeSettingsDto input)
        {
            var tenant = await TenantRepository.GetAsync(id);

            if (input.ThemeSettings != null)
            {
                var themeSettings = new Dictionary<string, object>(input.ThemeSettings);
                if (!string.IsNullOrEmpty(input.LogoUrl))
                    themeSettings["LogoUrl"] = input.LogoUrl;
                if (!string.IsNullOrEmpty(input.FaviconUrl))
                    themeSettings["FaviconUrl"] = input.FaviconUrl;
                if (!string.IsNullOrEmpty(input.CustomCss))
                    themeSettings["CustomCss"] = input.CustomCss;

                tenant.UpdateThemeSettings(JsonSerializer.Serialize(themeSettings));
            }

            await TenantRepository.UpdateAsync(tenant);

            // 清除缓存
            await TenantCache.RemoveAsync(tenant.Id.ToString());

            Logger.LogInformation("租户主题设置已更新: {TenantCode} ({TenantId})",
                tenant.Code, tenant.Id);

            return ObjectMapper.Map<Tenant, TenantDto>(tenant);
        }

        /// <summary>
        /// 获取租户统计信息
        /// </summary>
        [Authorize(TenantManagementPermissions.Tenants.Default)]
        public async Task<TenantStatisticsDto> GetStatisticsAsync()
        {
            var statistics = await TenantRepository.GetStatisticsAsync();

            var result = new TenantStatisticsDto
            {
                TotalCount = statistics.TotalCount,
                ActiveCount = statistics.ActiveCount,
                SuspendedCount = statistics.SuspendedCount,
                DisabledCount = statistics.DisabledCount,
                TrialCount = statistics.TrialCount,
                ExpiredCount = statistics.ExpiredCount,
                TypeDistribution = statistics.TypeDistribution,
                StatusDistribution = statistics.StatusDistribution,
                NewThisMonth = statistics.NewThisMonth,
                ActivatedThisMonth = statistics.ActivatedThisMonth,
                TotalUsers = statistics.TotalUsers,
                TotalStorageUsage = statistics.TotalStorageUsage
            };

            // 计算衍生统计
            if (statistics.TotalCount > 0)
            {
                result.AverageUserCount = Math.Round((double)statistics.TotalUsers / statistics.TotalCount, 2);
                result.AverageStorageUsage = Math.Round((double)statistics.TotalStorageUsage / statistics.TotalCount, 2);
                result.ActiveRate = Math.Round((double)statistics.ActiveCount / statistics.TotalCount * 100, 2);
            }

            if (statistics.TrialCount > 0)
            {
                result.TrialConversionRate = Math.Round((double)statistics.ActiveCount / (statistics.TrialCount + statistics.ActiveCount) * 100, 2);
            }

            return result;
        }

        /// <summary>
        /// 获取租户使用率统计
        /// </summary>
        [Authorize(TenantManagementPermissions.Tenants.Default)]
        public async Task<TenantUsageStatisticsDto> GetUsageStatisticsAsync(Guid id)
        {
            var tenant = await TenantRepository.GetAsync(id);
            var usageStats = await TenantRepository.GetUsageStatisticsAsync(id);

            return new TenantUsageStatisticsDto
            {
                TenantId = tenant.Id,
                TenantName = tenant.Name,
                TenantCode = tenant.Code,
                CurrentUserCount = usageStats.CurrentUserCount,
                MaxUserCount = usageStats.MaxUserCount,
                UserUsagePercentage = usageStats.UserUsagePercentage,
                CurrentStorageUsage = usageStats.CurrentStorageUsage,
                MaxStorageSize = usageStats.MaxStorageSize,
                StorageUsagePercentage = usageStats.StorageUsagePercentage,
                IsUserLimitExceeded = usageStats.IsUserLimitExceeded,
                IsStorageLimitExceeded = usageStats.IsStorageLimitExceeded,
                SubscriptionDaysRemaining = usageStats.SubscriptionDaysRemaining,
                IsExpiringSoon = usageStats.IsExpiringSoon,
                LastAccessTime = usageStats.LastAccessTime,
                LastAccessDescription = usageStats.LastAccessDescription
            };
        }

        /// <summary>
        /// 检查编码是否可用
        /// </summary>
        [AllowAnonymous]
        public async Task<bool> IsCodeAvailableAsync(string code, Guid? excludeId = null)
        {
            return !await TenantRepository.IsCodeExistsAsync(code, excludeId);
        }

        /// <summary>
        /// 检查主机是否可用
        /// </summary>
        [AllowAnonymous]
        public async Task<bool> IsHostAvailableAsync(string host, Guid? excludeId = null)
        {
            return !await TenantRepository.IsHostExistsAsync(host, excludeId);
        }

        /// <summary>
        /// 获取需要续期的租户
        /// </summary>
        [Authorize(TenantManagementPermissions.Tenants.Default)]
        public async Task<PagedResultDto<TenantDto>> GetTenantsNeedingRenewalAsync(GetTenantsNeedingRenewalDto input)
        {
            var tenants = await TenantRepository.GetTenantsNeedingRenewalAsync(input.DaysThreshold);

            if (input.Type.HasValue)
            {
                tenants = tenants.Where(t => t.Type == input.Type.Value).ToList();
            }

            var totalCount = tenants.Count;
            var items = tenants
                .OrderBy(t => t.SubscriptionEndTime)
                .Skip(input.SkipCount)
                .Take(input.MaxResultCount)
                .ToList();

            return new PagedResultDto<TenantDto>(
                totalCount,
                ObjectMapper.Map<List<Tenant>, List<TenantDto>>(items));
        }

        /// <summary>
        /// 获取过期的租户
        /// </summary>
        [Authorize(TenantManagementPermissions.Tenants.Default)]
        public async Task<PagedResultDto<TenantDto>> GetExpiredTenantsAsync(GetExpiredTenantsDto input)
        {
            var tenants = await TenantRepository.GetExpiredTenantsAsync();

            if (input.StartTime.HasValue)
                tenants = tenants.Where(t => t.SubscriptionEndTime >= input.StartTime.Value).ToList();

            if (input.EndTime.HasValue)
                tenants = tenants.Where(t => t.SubscriptionEndTime <= input.EndTime.Value).ToList();

            var totalCount = tenants.Count;
            var items = tenants
                .OrderByDescending(t => t.SubscriptionEndTime)
                .Skip(input.SkipCount)
                .Take(input.MaxResultCount)
                .ToList();

            return new PagedResultDto<TenantDto>(
                totalCount,
                ObjectMapper.Map<List<Tenant>, List<TenantDto>>(items));
        }

        /// <summary>
        /// 获取试用租户
        /// </summary>
        [Authorize(TenantManagementPermissions.Tenants.Default)]
        public async Task<PagedResultDto<TenantDto>> GetTrialTenantsAsync(GetTrialTenantsDto input)
        {
            var tenants = await TenantRepository.GetTrialTenantsAsync();

            if (input.StartTime.HasValue)
                tenants = tenants.Where(t => t.TrialStartTime >= input.StartTime.Value).ToList();

            if (input.EndTime.HasValue)
                tenants = tenants.Where(t => t.TrialEndTime <= input.EndTime.Value).ToList();

            if (input.ExpiringSoon)
            {
                var soonThreshold = DateTime.Now.AddDays(7);
                tenants = tenants.Where(t => t.TrialEndTime.HasValue && t.TrialEndTime.Value <= soonThreshold).ToList();
            }

            var totalCount = tenants.Count;
            var items = tenants
                .OrderBy(t => t.TrialEndTime)
                .Skip(input.SkipCount)
                .Take(input.MaxResultCount)
                .ToList();

            return new PagedResultDto<TenantDto>(
                totalCount,
                ObjectMapper.Map<List<Tenant>, List<TenantDto>>(items));
        }

        /// <summary>
        /// 获取超限租户
        /// </summary>
        [Authorize(TenantManagementPermissions.Tenants.Default)]
        public async Task<PagedResultDto<TenantDto>> GetTenantsWithLimitExceededAsync(GetTenantsWithLimitExceededDto input)
        {
            var tenants = new List<Tenant>();

            if (!input.LimitType.HasValue || input.LimitType == LimitType.UserCount)
            {
                var userLimitTenants = await TenantRepository.GetTenantsWithUserLimitExceededAsync();
                tenants.AddRange(userLimitTenants);
            }

            if (!input.LimitType.HasValue || input.LimitType == LimitType.Storage)
            {
                var storageLimitTenants = await TenantRepository.GetTenantsWithStorageLimitExceededAsync();
                tenants.AddRange(storageLimitTenants);
            }

            // 去重
            tenants = tenants.GroupBy(t => t.Id).Select(g => g.First()).ToList();

            if (input.ExceededPercentageThreshold.HasValue)
            {
                tenants = tenants.Where(t =>
                    (t.GetUserUsagePercentage() >= input.ExceededPercentageThreshold.Value) ||
                    (t.GetStorageUsagePercentage() >= input.ExceededPercentageThreshold.Value)).ToList();
            }

            var totalCount = tenants.Count;
            var items = tenants
                .OrderByDescending(t => new[] { t.GetUserUsagePercentage(), t.GetStorageUsagePercentage() }.Max())
                .Skip(input.SkipCount)
                .Take(input.MaxResultCount)
                .ToList();

            return new PagedResultDto<TenantDto>(
                totalCount,
                ObjectMapper.Map<List<Tenant>, List<TenantDto>>(items));
        }

        /// <summary>
        /// 搜索租户
        /// </summary>
        [Authorize(TenantManagementPermissions.Tenants.Default)]
        public async Task<PagedResultDto<TenantDto>> SearchAsync(SearchTenantsDto input)
        {
            var tenants = await TenantRepository.SearchAsync(
                input.Keyword,
                input.Type,
                input.Status,
                1000); // 使用固定的最大返回数量

            if (input.IsEnabled.HasValue)
            {
                tenants = tenants.Where(t => t.IsEnabled == input.IsEnabled.Value).ToList();
            }

            var totalCount = tenants.Count;
            var items = ApplySorting(tenants.AsQueryable(), input)
                .Skip(input.SkipCount)
                .Take(input.MaxResultCount)
                .ToList();

            return new PagedResultDto<TenantDto>(
                totalCount,
                ObjectMapper.Map<List<Tenant>, List<TenantDto>>(items));
        }

        /// <summary>
        /// 批量操作租户
        /// </summary>
        [Authorize(TenantManagementPermissions.Tenants.Manage)]
        public async Task<BatchOperationResultDto> BatchOperateAsync(BatchOperationTenantDto input)
        {
            var result = new BatchOperationResultDto
            {
                TotalCount = input.TenantIds.Count,
                StartTime = DateTime.Now
            };

            foreach (var tenantId in input.TenantIds)
            {
                try
                {
                    var tenant = await TenantRepository.GetAsync(tenantId);

                    switch (input.Operation)
                    {
                        case BatchOperationType.Activate:
                            tenant.Activate();
                            break;
                        case BatchOperationType.Suspend:
                            tenant.Suspend();
                            break;
                        case BatchOperationType.Disable:
                            tenant.Disable();
                            break;
                        case BatchOperationType.Enable:
                            tenant.Enable();
                            break;
                        case BatchOperationType.Extend:
                            var days = input.Parameters?.GetValueOrDefault("Days", 30) as int? ?? 30;
                            tenant.ExtendSubscription(TimeSpan.FromDays(days));
                            break;
                        case BatchOperationType.Delete:
                            // 软删除
                            tenant.Disable();
                            break;
                    }

                    await TenantRepository.UpdateAsync(tenant);
                    await TenantCache.RemoveAsync(tenantId.ToString());

                    result.SuccessIds.Add(tenantId);
                    result.SuccessCount++;
                }
                catch (Exception ex)
                {
                    result.FailureIds.Add(tenantId);
                    result.Failures.Add(new ImportFailureRecord
                    {
                        RowNumber = result.FailureCount + 1,
                        ErrorMessage = ex.Message,
                        ErrorType = ex.GetType().Name,
                        Suggestion = "检查租户状态和操作权限"
                    });
                    result.FailureCount++;
                }
            }

            result.EndTime = DateTime.Now;
            result.DurationMs = (long)(result.EndTime - result.StartTime).TotalMilliseconds;

            return result;
        }

        /// <summary>
        /// 导出租户列表
        /// </summary>
        [Authorize(TenantManagementPermissions.Tenants.Export)]
        public async Task<FileDto> ExportAsync(ExportTenantsDto input)
        {
            var queryable = await Repository.GetQueryableAsync();

            if (input.Type.HasValue)
                queryable = queryable.Where(t => t.Type == input.Type.Value);

            if (input.Status.HasValue)
                queryable = queryable.Where(t => t.Status == input.Status.Value);

            var tenants = await AsyncExecuter.ToListAsync(queryable);
            var dtos = ObjectMapper.Map<List<Tenant>, List<TenantDto>>(tenants);

            // 根据格式导出
            var fileName = $"tenants_export_{DateTime.Now:yyyyMMdd_HHmmss}";
            byte[] fileData;

            switch (input.Format)
            {
                case ExportFormat.Excel:
                    fileData = await ExportToExcelAsync(dtos, input);
                    fileName += ".xlsx";
                    break;
                case ExportFormat.Csv:
                    fileData = await ExportToCsvAsync(dtos, input);
                    fileName += ".csv";
                    break;
                case ExportFormat.Json:
                    fileData = await ExportToJsonAsync(dtos, input);
                    fileName += ".json";
                    break;
                default:
                    throw new BusinessException("TenantManagement:UnsupportedExportFormat");
            }

            return new FileDto(fileName, "application/octet-stream", fileData);
        }

        /// <summary>
        /// 导入租户列表
        /// </summary>
        [Authorize(TenantManagementPermissions.Tenants.Import)]
        public async Task<ImportResultDto> ImportAsync(ImportTenantsDto input)
        {
            var result = new ImportResultDto
            {
                StartTime = DateTime.Now
            };

            try
            {
                // 根据格式解析文件
                List<TenantDto> tenants;
                switch (input.Format)
                {
                    case ImportFormat.Excel:
                        tenants = await ParseFromExcelAsync(input);
                        break;
                    case ImportFormat.Json:
                        tenants = await ParseFromJsonAsync(input);
                        break;
                    default:
                        throw new BusinessException("TenantManagement:UnsupportedImportFormat");
                }

                result.TotalRecords = tenants.Count;

                // 验证和处理每个租户
                foreach (var (tenantDto, index) in tenants.Select((t, i) => (t, i + 1)))
                {
                    try
                    {
                        // 验证数据
                        if (input.ValidateData)
                        {
                            await ValidateTenantDataAsync(tenantDto);
                        }

                        // 检查是否已存在
                        var existingTenant = await TenantRepository.FindByCodeAsync(tenantDto.Code);
                        if (existingTenant != null)
                        {
                            if (input.OverwriteExisting)
                            {
                                // 更新现有租户
                                var updateDto = ObjectMapper.Map<TenantDto, UpdateTenantDto>(tenantDto);
                                await UpdateAsync(existingTenant.Id, updateDto);
                                result.UpdatedCount++;
                            }
                            else
                            {
                                // 跳过
                                result.SkippedIds.Add(existingTenant.Id);
                                result.Failures.Add(new ImportFailureRecord
                                {
                                    RowNumber = index,
                                    RawData = JsonSerializer.Deserialize<Dictionary<string, object>>(
                                        JsonSerializer.Serialize(tenantDto)),
                                    ErrorMessage = "租户编码已存在且不允许覆盖",
                                    ErrorType = "Duplicate",
                                    Suggestion = "使用覆盖选项或修改租户编码"
                                });
                            }
                        }
                        else
                        {
                            // 创建新租户
                            var createDto = ObjectMapper.Map<TenantDto, CreateTenantDto>(tenantDto);
                            await CreateAsync(createDto);
                            result.SuccessCount++;
                        }
                    }
                    catch (Exception ex)
                    {
                        result.Failures.Add(new ImportFailureRecord
                        {
                            RowNumber = index,
                            RawData = JsonSerializer.Deserialize<Dictionary<string, object>>(
                                JsonSerializer.Serialize(tenantDto)),
                            ErrorMessage = ex.Message,
                            ErrorType = ex.GetType().Name,
                            Suggestion = "检查数据格式和必填字段"
                        });
                    }
                }

                result.SuccessTenants = ObjectMapper.Map<List<TenantDto>, List<TenantDto>>(tenants);
            }
            catch (Exception ex)
            {
                Logger.LogError(ex, "导入租户时发生错误");
                throw;
            }
            finally
            {
                result.EndTime = DateTime.Now;
                result.DurationMs = (long)(result.EndTime - result.StartTime).TotalMilliseconds;
            }

            return result;
        }

        /// <summary>
        /// 获取租户代码列表
        /// </summary>
        [Authorize(TenantManagementPermissions.Tenants.Default)]
        public async Task<List<string>> GetCodesAsync(bool? isEnabled = null)
        {
            return await TenantRepository.GetCodesAsync(isEnabled);
        }

        /// <summary>
        /// 重置租户密码
        /// </summary>
        [Authorize(TenantManagementPermissions.Tenants.Manage)]
        public async Task ResetAdminPasswordAsync(Guid id, ResetAdminPasswordDto input)
        {
            var tenant = await TenantRepository.GetAsync(id);

            // 生成新密码（如果未提供）
            var newPassword = input.NewPassword ?? GenerateRandomPassword();

            // TODO: 调用用户服务重置管理员密码
            // await _userService.ResetAdminPasswordAsync(tenant.AdminEmail, newPassword);

            if (input.SendEmailNotification && !string.IsNullOrEmpty(tenant.AdminEmail))
            {
                // TODO: 发送密码重置邮件
                // await _emailSender.SendPasswordResetEmailAsync(tenant.AdminEmail, newPassword);
            }

            Logger.LogInformation("租户管理员密码已重置: {TenantCode} ({TenantId})",
                tenant.Code, tenant.Id);
        }

        /// <summary>
        /// 验证租户
        /// </summary>
        [Authorize(TenantManagementPermissions.Tenants.Default)]
        public async Task<ValidationResultDto> ValidateAsync(Guid id)
        {
            var tenant = await TenantRepository.GetAsync(id);
            var result = new ValidationResultDto
            {
                ValidationTime = DateTime.Now
            };

            var validationItems = new List<ValidationItemDto>();

            // 验证基本信息
            validationItems.Add(new ValidationItemDto
            {
                Name = "BasicInfo",
                Description = "基本信息验证",
                IsPassed = !string.IsNullOrEmpty(tenant.Code) && !string.IsNullOrEmpty(tenant.Name),
                Score = !string.IsNullOrEmpty(tenant.Code) && !string.IsNullOrEmpty(tenant.Name) ? 100 : 50,
                Message = !string.IsNullOrEmpty(tenant.Code) && !string.IsNullOrEmpty(tenant.Name) ? "基本信息完整" : "基本信息不完整"
            });

            // 验证管理员信息
            validationItems.Add(new ValidationItemDto
            {
                Name = "AdminInfo",
                Description = "管理员信息验证",
                IsPassed = !string.IsNullOrEmpty(tenant.AdminEmail),
                Score = !string.IsNullOrEmpty(tenant.AdminEmail) ? 100 : 0,
                Message = !string.IsNullOrEmpty(tenant.AdminEmail) ? "管理员信息完整" : "缺少管理员邮箱"
            });

            // 验证连接信息
            validationItems.Add(new ValidationItemDto
            {
                Name = "ConnectionInfo",
                Description = "连接信息验证",
                IsPassed = !string.IsNullOrEmpty(tenant.ConnectionString) || !string.IsNullOrEmpty(tenant.Host),
                Score = (!string.IsNullOrEmpty(tenant.ConnectionString) || !string.IsNullOrEmpty(tenant.Host)) ? 100 : 50,
                Message = (!string.IsNullOrEmpty(tenant.ConnectionString) || !string.IsNullOrEmpty(tenant.Host)) ? "连接信息完整" : "缺少连接信息"
            });

            // 验证订阅状态
            validationItems.Add(new ValidationItemDto
            {
                Name = "SubscriptionStatus",
                Description = "订阅状态验证",
                IsPassed = !tenant.IsExpired(),
                Score = tenant.IsExpired() ? 0 : 100,
                Message = tenant.IsExpired() ? "订阅已过期" : "订阅状态正常"
            });

            // 验证使用量
            var userLimitExceeded = tenant.IsUserLimitExceeded();
            var storageLimitExceeded = tenant.IsStorageLimitExceeded();
            validationItems.Add(new ValidationItemDto
            {
                Name = "UsageLimits",
                Description = "使用量限制验证",
                IsPassed = !userLimitExceeded && !storageLimitExceeded,
                Score = (userLimitExceeded || storageLimitExceeded) ? 30 : 100,
                Message = userLimitExceeded ? "用户数超限" : storageLimitExceeded ? "存储空间超限" : "使用量正常"
            });

            result.ValidationItems = validationItems;
            result.IsValid = validationItems.All(item => item.IsPassed);
            result.OverallScore = validationItems.Average(item => item.Score);

            // 确定风险等级
            if (result.OverallScore >= 80)
                result.RiskLevel = RiskLevel.Low;
            else if (result.OverallScore >= 60)
                result.RiskLevel = RiskLevel.Medium;
            else if (result.OverallScore >= 40)
                result.RiskLevel = RiskLevel.High;
            else
                result.RiskLevel = RiskLevel.Critical;

            // 生成建议
            if (!result.IsValid)
            {
                var failedItems = result.ValidationItems.Where(item => !item.IsPassed);
                foreach (var item in failedItems)
                {
                    result.Recommendations.Add($"建议修复{item.Description}: {item.Message}");
                }
            }

            return result;
        }

        /// <summary>
        /// 获取租户配置
        /// </summary>
        [Authorize(TenantManagementPermissions.Tenants.Default)]
        public async Task<TenantConfigurationsDto> GetConfigurationsAsync(Guid id)
        {
            var tenant = await TenantRepository.GetAsync(id);
            var configurations = await ConfigurationRepository.GetListAsync(c => c.TenantId == id);

            var configurationDtos = ObjectMapper.Map<List<TenantConfiguration>, List<TenantConfigurationDto>>(configurations);

            var result = new TenantConfigurationsDto
            {
                TenantId = tenant.Id,
                TenantName = tenant.Name,
                Configurations = configurationDtos
            };

            // 按组分组
            result.GroupedConfigurations = configurationDtos
                .Where(c => !string.IsNullOrEmpty(c.Group))
                .GroupBy(c => c.Group!)
                .ToDictionary(g => g.Key, g => g.ToList());

            return result;
        }

        /// <summary>
        /// 更新租户配置
        /// </summary>
        [Authorize(TenantManagementPermissions.Tenants.Manage)]
        public async Task UpdateConfigurationAsync(Guid id, UpdateTenantConfigurationDto input)
        {
            var tenant = await TenantRepository.GetAsync(id);

            // 检查配置是否已存在
            var existingConfig = await ConfigurationRepository.FirstOrDefaultAsync(c => c.TenantId == id && c.Key == input.Key);

            if (existingConfig != null)
            {
                // 更新现有配置
                existingConfig.UpdateValue(input.Value);
                existingConfig.SetGroup(input.Group);
                existingConfig.SetDescription(input.Description);
                existingConfig.SetEncryption(input.IsEncrypted);

                await ConfigurationRepository.UpdateAsync(existingConfig);
            }
            else
            {
                // 创建新配置
                var configuration = new TenantConfiguration(
                    GuidGenerator.Create(),
                    id,
                    input.Key,
                    input.Value,
                    ConfigurationType.String);

                configuration.SetGroup(input.Group);
                configuration.SetDescription(input.Description);
                configuration.SetEncryption(input.IsEncrypted);

                await ConfigurationRepository.InsertAsync(configuration);
            }

            // 清除租户配置缓存
            await TenantCache.RemoveAsync($"tenant_config_{id}_{input.Key}");

            Logger.LogInformation("租户配置已更新: {TenantCode} ({TenantId}) - {Key}",
                tenant.Code, tenant.Id, input.Key);
        }

        #region 重写方法

        /// <summary>
        /// 创建租户
        /// </summary>
        public override async Task<TenantDto> CreateAsync(CreateTenantDto input)
        {
            // 检查编码唯一性
            if (await TenantRepository.IsCodeExistsAsync(input.Code))
            {
                throw new BusinessException("TenantManagement:DuplicateTenantCode")
                    .WithData("Code", input.Code);
            }

            // 手动创建Tenant实体，避免AutoMapper的复杂映射
            var tenant = new Tenant(
                GuidGenerator.Create(),
                input.Code,
                input.Name,
                input.Type);

            // 设置其他属性
            if (!string.IsNullOrEmpty(input.Description))
                tenant.UpdateBasicInfo(input.Name, input.Description, input.LogoUrl);

            if (!string.IsNullOrEmpty(input.ConnectionString) || !string.IsNullOrEmpty(input.Host))
                tenant.SetConnectionInfo(input.ConnectionString, input.Host);

            if (!string.IsNullOrEmpty(input.AdminEmail))
                tenant.SetAdminInfo(input.AdminEmail, input.AdminPhoneNumber);

            if (input.Settings != null)
                tenant.UpdateSettings(JsonSerializer.Serialize(input.Settings));

            if (input.CustomProperties != null)
                tenant.UpdateCustomProperties(JsonSerializer.Serialize(input.CustomProperties));

            if (input.FeatureSwitches != null)
                tenant.UpdateFeatureSwitches(JsonSerializer.Serialize(input.FeatureSwitches));

            if (input.ThemeSettings != null)
                tenant.UpdateThemeSettings(JsonSerializer.Serialize(input.ThemeSettings));

            // 如果需要自动激活
            if (input.AutoActivate)
            {
                tenant.Activate();
            }

            await TenantRepository.InsertAsync(tenant, autoSave: true);

            // 创建默认配置
            await CreateDefaultConfigurationsAsync(tenant.Id);

            // 发布事件
            await EventBus.PublishAsync(new TenantCreatedEvent
            {
                TenantId = tenant.Id,
                Code = tenant.Code,
                Name = tenant.Name,
                Type = tenant.Type,
                Status = tenant.Status,
                AdminEmail = tenant.AdminEmail,
                TrialStartTime = tenant.TrialStartTime,
                TrialEndTime = tenant.TrialEndTime,
                MaxUserCount = tenant.MaxUserCount,
                MaxStorageSize = tenant.MaxStorageSize,
                CreationTime = tenant.CreationTime,
                CreatorId = CurrentUser.Id?.ToString(),
                Configurations = JsonSerializer.Deserialize<Dictionary<string, object>>(tenant.Settings ?? "{}"),
                FeatureSwitches = JsonSerializer.Deserialize<Dictionary<string, bool>>(tenant.FeatureSwitches ?? "{}")
            });

            Logger.LogInformation("租户已创建: {TenantCode} ({TenantId})", tenant.Code, tenant.Id);

            return ObjectMapper.Map<Tenant, TenantDto>(tenant);
        }

        /// <summary>
        /// 更新租户
        /// </summary>
        public override async Task<TenantDto> UpdateAsync(Guid id, UpdateTenantDto input)
        {
            var tenant = await TenantRepository.GetAsync(id);

            // 记录更新的字段
            var updatedFields = new List<string>();
            var oldValues = new Dictionary<string, object>();
            var newValues = new Dictionary<string, object>();

            if (input.Name != null && input.Name != tenant.Name)
            {
                oldValues["Name"] = tenant.Name;
                newValues["Name"] = input.Name;
                updatedFields.Add("Name");
            }

            if (input.Description != null && input.Description != tenant.Description)
            {
                oldValues["Description"] = tenant.Description;
                newValues["Description"] = input.Description;
                updatedFields.Add("Description");
            }

            // 应用更新
            ObjectMapper.Map(input, tenant);

            await TenantRepository.UpdateAsync(tenant, autoSave: true);

            // 清除缓存
            await TenantCache.RemoveAsync(tenant.Id.ToString());

            // 如果有字段更新，发布事件
            if (updatedFields.Any())
            {
                await EventBus.PublishAsync(new TenantUpdatedEvent
                {
                    TenantId = tenant.Id,
                    Code = tenant.Code,
                    UpdateTime = DateTime.Now,
                    UpdaterId = CurrentUser.Id?.ToString(),
                    UpdatedFields = updatedFields,
                    OldValues = oldValues,
                    NewValues = newValues
                });
            }

            Logger.LogInformation("租户已更新: {TenantCode} ({TenantId})", tenant.Code, tenant.Id);

            return ObjectMapper.Map<Tenant, TenantDto>(tenant);
        }

        /// <summary>
        /// 删除租户
        /// </summary>
        public override async Task DeleteAsync(Guid id)
        {
            var tenant = await TenantRepository.GetAsync(id);

            // 检查是否可以删除
            if (tenant.Status == TenantStatus.Active && tenant.CurrentUserCount > 0)
            {
                throw new BusinessException("TenantManagement:CannotDeleteActiveTenant")
                    .WithData("TenantCode", tenant.Code)
                    .WithData("UserCount", tenant.CurrentUserCount);
            }

            // 软删除（禁用）
            tenant.Disable();
            await TenantRepository.UpdateAsync(tenant);

            // 清除缓存
            await TenantCache.RemoveAsync(tenant.Id.ToString());

            Logger.LogInformation("租户已删除: {TenantCode} ({TenantId})", tenant.Code, tenant.Id);
        }

        #endregion

        #region 私有方法

        private async Task TestDatabaseConnectionAsync(string connectionString)
        {
            // TODO: 实现数据库连接测试
            // 这里可以使用指定的连接字符串尝试连接数据库
            // throw new BusinessException("TenantManagement:ConnectionTestFailed") if connection fails

            Logger.LogDebug("测试数据库连接: {ConnectionString}", connectionString);
            await Task.CompletedTask;
        }

        private async Task<byte[]> ExportToExcelAsync(List<TenantDto> tenants, ExportTenantsDto input)
        {
            // TODO: 实现Excel导出逻辑
            // 使用EPPlus或类似的库来生成Excel文件
            await Task.CompletedTask;

            var json = JsonSerializer.Serialize(tenants, new JsonSerializerOptions { WriteIndented = true });
            return System.Text.Encoding.UTF8.GetBytes(json);
        }

        private async Task<byte[]> ExportToCsvAsync(List<TenantDto> tenants, ExportTenantsDto input)
        {
            // TODO: 实现CSV导出逻辑
            await Task.CompletedTask;

            var json = JsonSerializer.Serialize(tenants, new JsonSerializerOptions { WriteIndented = true });
            return System.Text.Encoding.UTF8.GetBytes(json);
        }

        private async Task<byte[]> ExportToJsonAsync(List<TenantDto> tenants, ExportTenantsDto input)
        {
            // TODO: 实现JSON导出逻辑
            await Task.CompletedTask;

            var json = JsonSerializer.Serialize(tenants, new JsonSerializerOptions { WriteIndented = true });
            return System.Text.Encoding.UTF8.GetBytes(json);
        }

        private async Task<List<TenantDto>> ParseFromExcelAsync(ImportTenantsDto input)
        {
            // TODO: 实现Excel解析逻辑
            await Task.CompletedTask;

            return new List<TenantDto>();
        }

        private async Task<List<TenantDto>> ParseFromJsonAsync(ImportTenantsDto input)
        {
            // TODO: 实现JSON解析逻辑
            await Task.CompletedTask;

            return new List<TenantDto>();
        }

        private async Task ValidateTenantDataAsync(TenantDto tenant)
        {
            // 验证必填字段
            if (string.IsNullOrEmpty(tenant.Code))
                throw new BusinessException("TenantManagement:TenantCodeRequired");

            if (string.IsNullOrEmpty(tenant.Name))
                throw new BusinessException("TenantManagement:TenantNameRequired");

            // 验证编码格式
            if (!System.Text.RegularExpressions.Regex.IsMatch(tenant.Code, @"^[a-zA-Z0-9_-]+$"))
                throw new BusinessException("TenantManagement:InvalidTenantCode");

            await Task.CompletedTask;
        }

        private async Task CreateDefaultConfigurationsAsync(Guid tenantId)
        {
            var defaultConfigs = new List<TenantConfiguration>
            {
                new TenantConfiguration(
                    GuidGenerator.Create(),
                    tenantId,
                    "TimeZone",
                    "Asia/Shanghai",
                    ConfigurationType.String)
                .SetGroup("General")
                .SetDescription("租户时区设置"),
                new TenantConfiguration(
                    GuidGenerator.Create(),
                    tenantId,
                    "Language",
                    "zh-CN",
                    ConfigurationType.String)
                .SetGroup("General")
                .SetDescription("租户语言设置"),
                new TenantConfiguration(
                    GuidGenerator.Create(),
                    tenantId,
                    "EnableNotifications",
                    "true",
                    ConfigurationType.Boolean)
                .SetGroup("Features")
                .SetDescription("是否启用通知功能")
            };

            foreach (var config in defaultConfigs)
            {
                await ConfigurationRepository.InsertAsync(config);
            }

            await Task.CompletedTask;
        }

        private string GenerateRandomPassword()
        {
            const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*";
            var random = new Random();
            return new string(Enumerable.Repeat(chars, 12)
                .Select(s => s[random.Next(s.Length)]).ToArray());
        }

        #endregion
    }

    /// <summary>
    /// 租户缓存项
    /// </summary>
    public class TenantCacheItem
    {
        public TenantDto? Tenant { get; set; }
        public Dictionary<string, string>? Configurations { get; set; }
        public DateTime? LastUpdated { get; set; }
    }

    /// <summary>
    /// 租户管理权限定义
    /// </summary>
    public static class TenantManagementPermissions
    {
        public const string GroupName = "TenantManagement";

        public static class Tenants
        {
            public const string Default = GroupName + ".Tenants";
            public const string Create = Default + ".Create";
            public const string Edit = Default + ".Edit";
            public const string Delete = Default + ".Delete";
            public const string Manage = Default + ".Manage";
            public const string Export = Default + ".Export";
            public const string Import = Default + ".Import";
        }
    }
}